package erfgame.core.world.terrain.file;

import java.awt.Point;
import java.io.File;

import erfgame.core.dao.ObjectDAO;

public final class FileXYObjectDAO<T> extends BaseFileObjectDAO<T> implements ObjectDAO<Point, T> {

	private String extension;
	private File directory;
	
	public FileXYObjectDAO( FileStreamFactory streamFactory, Serializer<T> serializer, File directory, String extension ) {
		super( serializer, streamFactory );
		this.extension = extension;
		this.directory = directory;
	}
	
	public T retrieveObject(Point key) {
		return retrieveObject(getFile(key.x,key.y), null);
	}

	public void storeObject(Point key, T object) {
		storeObject(getFile(key.x,key.y), object);
	}
	
	public boolean containsObject(Point key) {
		File file = getFile( key.x, key.y );
		return file.exists();
	}

	public boolean removeObject(Point key) {
		File file = getFile( key.x, key.y );
		boolean exists = file.exists();
		if( exists ) {
			file.delete();
		}
		return exists;
	}

	private final File getFile( int x, int y ) {
		StringBuffer sb = new StringBuffer(16);
		sb.append(x);
		sb.append('x');
		sb.append(y);
		sb.append('.');
		sb.append(this.extension);
		return new File( directory, sb.toString() );
	}
}
